package com.rentdvd.client.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rentdvd.ws.RentDVDImplProxy;

@WebServlet("/movie")
public class MovieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public MovieServlet() {
		super();
	}
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RentDVDImplProxy service = new RentDVDImplProxy();
		String result = null;
		
		PrintWriter pw = response.getWriter();
		response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
		
		if (request.getQueryString().equals("getCatalog")) {
			result = service.getCatalog();
		} else if (request.getQueryString().contains("recommend")) {
			//TODO : here only string! not xml
			
			String city = request.getParameter("city");
			result = "<?xml version='1.0' encoding='UTF-16'?> <movies xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'	xsi:noNamespaceSchemaLocation='catalog.xsd'>";
			
			try {
				result += service.recommendMovie((String) request.getSession().getAttribute("username"), city);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			
			result += "</movies>";
		} else if (request.getQueryString().equals("getHistory")) {
			result = "<?xml version='1.0' encoding='UTF-16'?> <movies xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'	xsi:noNamespaceSchemaLocation='catalog.xsd'>";
			
			try {
				result += service.getWatchedMoviesAsXML((String) request.getSession().getAttribute("username"));
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			
			result += "</movies>";
			
		}
		pw.write(result);
		pw.flush();
	}
}